package com.sunwayworld.common.utils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
import java.text.*;

import java.util.StringTokenizer;

/**
 * Title: SafeString Description: this class is used to manage the String
 * variable even it is null. Copyright: Copyright (c) 2001 Company:
 * 
 * @author
 * @version 1.0
 */

public class SafeString {

	public static String safeDate(Object str) {
		if (str == null) {
			return "";
		}
		try {
			if (str instanceof java.util.Date) {
				return DateFormat.formatDate((java.util.Date) str);
			} else

			if (str instanceof java.sql.Date) {
				return DateFormat.formatDate((java.sql.Date) str);
			} else {

				Date d = DateFormat.parseDate(str.toString());
				return DateFormat.formatDate(d);
			}

		} catch (Exception ex) {
			System.out.println("data 3 " + ex.getMessage());
			return "";
		}

	}

	/**
	 * use private constructor to establish a singleton pattern
	 */
	private SafeString() {
	}

	public static String roundNumber(double d, int n) {
		// 200-01-17 add by liyimin
		// 去掉-0
		if (d == 0) {
			d = 0;
		}

		if (n < 0) {
			n = 0;
		}
		String str = "";
		if (n == 0) {
			str = "0";
		} else {
			str = "0.";
		}
		for (int i = 0; i < n; i++) {
			str = str + "0";
		}
		DecimalFormat formater = new DecimalFormat(str);
		double tempd = Double.parseDouble(formater.format(d));
		if (tempd == 0) {
			tempd = 0;
		}
		return formater.format(tempd);
	}

	public static String roundNumber(Double d, int n) {
		if (d == null) {
			d = new Double(0);
		}
		return roundNumber(d.doubleValue(), n);
	}

	public static String roundNumber2(Double d, int n) {
		if (d == null) {
			d = new Double(0);
		}
		if (n < 0) {
			n = 0;
		}
		String str = "";
		if (n == 0) {
			str = "#";
		} else {
			str = "#.";
		}
		for (int i = 0; i < n; i++) {
			str = str + "#";
		}
		DecimalFormat formater = new DecimalFormat(str);

		return formater.format(d);
	}

	public static double roundNumber2(double d, int n) {
		return Double.parseDouble(roundNumber(d, n));
	}

	public static double roundJeD(double src) {
		return roundJeD(new Double(src));
	}

	public static double roundJeD(Object src) {
		Double d = null;
		if (src == null) {
			d = new Double(0);
		}
		try {
			d = new Double(src.toString());
		} catch (Exception ex) {

		}
		return roundJeD(d);
	}

	public static double roundJeD(Double src) {
		if (src == null) {
			src = new Double("0");
		}

		return Double.parseDouble(roundNumber(src.doubleValue(), 2));
	}

	public static double roundSlD(double src) {
		return roundSlD(new Double(src));
	}

	public static double roundSlD(Object src) {
		Double d = null;
		if (src == null) {
			d = new Double(0);
		}
		try {
			d = new Double(src.toString());
		} catch (Exception ex) {

		}
		return roundSlD(d);
	}

	public static double roundSlD(Double src) {
		if (src == null) {
			src = new Double("0");
		}

		return Double.parseDouble(roundNumber(src.doubleValue(), 3));
	}

	/**
	 * check whether the String is null or "" after trimimg space
	 */
	public static boolean isEmpty(String str) {
		return (str == null || "".equals(str.trim()));
	}

	/**
	 * return string length
	 */
	public static int strlen(String str) {
		if (isEmpty(str)) {
			return 0;
		}
		return str.length();
	}

	public static String safeString(Object str) {
		if (str == null) {
			return "";
		} else {
			return SafeString.safeString(str.toString());
		}

	}

	/**
	 * 将str字符中的引号替换成 &quot;，用成在html页面里显示 上一个方法也是的，但是是错误的 此方法在支持 jdk1.4以上的版本使用
	 * 
	 * @param str
	 * @return
	 */
	// public static String safeStringQuot(String str) {
	// if (str == null) {
	// return "";
	// }
	// str = str.trim();
	// str = str.replaceAll("\"", "&quot;");
	// return str;
	// }
	public static String safeString(String str) {
		if (str == null) {
			return "";
		}
		str = str.trim();

		return str;
	}

	// ZXZ 20030918 更改更换的方法 原更换方法有问题
	// -- modified by LiuGan at 2005/08/03，原来有错误
	public static String getReplace(String sb, String strSrc, String strDst) {

		StringBuffer sbReturn = new StringBuffer();

		int sblen = sb.length();
		int strlen = strSrc.length();
		if (strlen <= 0) {
			return sb;
		}

		for (int i = 0; i < sblen; i++) {
			int endIndex = i + strlen;
			if (endIndex > sblen) {
				// endIndex = ( (endIndex * 2) - sblen);
				sbReturn.append(sb.substring(i, sblen));
				break;
			}
			String tmpStr = sb.substring(i, endIndex);
			if (tmpStr.equals(strSrc)) {
				sbReturn.append(strDst);
				// i += strlen;
				i += strlen - 1;
			} else {
				sbReturn.append(sb.charAt(i));
			}
		}

		return new String(sbReturn);

	}

	/**
	 * return a int parsed from the string if the str is null or can not be
	 * parsed to a integer will return 0
	 * 
	 * @param string
	 *            to parse
	 * 
	 * @return int of result
	 */
	public static int safeInt(String str) {
		if (str == null) {
			return 0;
		}

		int ret = 0;
		try {
			ret = Integer.parseInt(str.trim());
		} catch (Exception e) {
			ret = 0;
		}
		return ret;
	}

	/**
	 * return a double parsed from the string if the str is null or can not be
	 * parsed to a double will return 0.0
	 * 
	 * @param string
	 *            to parse
	 * 
	 * @return double of result
	 */
	public static double safeDouble(String str) {
		if (str == null) {
			return 0.0;
		}

		double ret = 0.0;
		try {
			ret = Double.parseDouble(str.trim());
		} catch (Exception e) {
			ret = 0.0;
		}
		return ret;
	}

	public static double safeDouble(Double str) {
		if (str == null) {
			return 0;
		}

		return str.doubleValue();
	}

	/**
	 * return a string if is null or " " return "&nbsp;"
	 * 
	 * @param str
	 *            The string to check
	 * @return if the string is null or "" return "&nbsp;" otherwise is itself
	 */
	public static String tdString(String str) {
		if (isEmpty(str)) {
			return "&nbsp;";
		}
		return str;
	}

	public static int tdString(int src) {
		return src;
	}

	public static double tdString(double src) {
		return src;
	}

	public static String tdString(Double src) {
		if (src == null) {
			return "";
		} else {
			return src.toString();
		}

	}

	public static String roundJe(Double src) {

		if (src == null) {
			src = new Double("0");
		}
		return roundNumber(src.doubleValue(), 2);
	}

	public static String roundJe(Object src) {
		Double d = new Double(0);
		if (src == null) {
			src = new Double("0");
		}
		try {
			d = new Double(src.toString());
		} catch (Exception ex) {

		}
		return roundNumber(d.doubleValue(), 2);
	}

	/**
	 * 带千分位的金额
	 * 
	 * @param src
	 *            Double
	 * @return String
	 */
	public static String roundJe2(Double src) {
		DecimalFormat dfm = new DecimalFormat("##,##0.00");
		if (src == null) {
			src = new Double("0");
		}
		return dfm.format(src.doubleValue());
	}

	public static String roundSl(Double src) {

		if (src == null) {
			src = new Double("0");
		}
		return roundNumber(src.doubleValue(), 3);
	}

	public static String roundSl(Object src) {
		Double d = new Double(0);
		if (src == null) {
			src = new Double("0");
		}
		try {
			d = new Double(src.toString());
		} catch (Exception ex) {

		}

		return roundNumber(d.doubleValue(), 3);
	}

	public static String tdString(Object src) {
		if (src == null) {
			return "&nbsp;";
		}
		return src.toString();
	}

	public static String tdString(java.util.Date src) {
		if (src == null) {
			return "&nbsp;";
		}
		return src.toString();
	}

	public static String tdString(Float src) {
		if (src == null) {
			return "&nbsp;";
		}
		return src.toString();
	}

	public static String tdString(float f) {
		Float src = new Float(f);
		if (src == null) {
			return "&nbsp;";
		}
		return src.toString();
	}

	public static String tdString(java.sql.Date src) {
		if (src == null) {
			return "&nbsp;";
		}
		return src.toString();
	}

	public static String getSpace(int num) {
		if (num <= 0) {
			return "";
		}
		StringBuffer buf = new StringBuffer(num * 5 + 10);
		for (int i = 0; i < num; i++) {
			buf.append("&nbsp;");
		}

		return buf.toString();
	}

	/**
	 * 处理数据位数
	 * 
	 * @param sdate:要截位的数据
	 * @param scale：小数位数
	 * @return：已截位的数据(四舍五入）
	 */
	public static double DoDigit(double sdate, int scale) {

		BigDecimal bSdate = new BigDecimal(sdate);

		sdate = bSdate.doubleValue();
		return sdate;
	}

	/**
	 * 时间相加
	 * 
	 * @param sdate:时间
	 * @param scale：天数
	 * @return：已截位的数据(四舍五入）
	 */
	public static Date DoDate(Date sdate, int ntime) {

		Calendar clen = Calendar.getInstance(Locale.CHINESE);
		if (sdate == null) {
			sdate = new Date();
		}
		clen.setTime(sdate);
		clen.add(Calendar.DAY_OF_MONTH, ntime);
		sdate = clen.getTime();
		return sdate;
	}

	/**
	 * 时间相加
	 * 
	 * @param sdate:时间
	 * @param scale：天数
	 * @return：已截位的数据(四舍五入）
	 */
	public static Date DoDate(String date, int ntime) {

		Calendar clen = Calendar.getInstance(Locale.CHINESE);
		Date sdate = null;
		try {
			sdate = DateFormat.parseDate(safeString(date));
		} catch (Exception ex) {
			sdate = new Date();
		}

		if (sdate == null) {
			sdate = new Date();
		}

		clen.setTime(sdate);
		clen.add(Calendar.DAY_OF_MONTH, ntime);
		sdate = clen.getTime();

		return sdate;
	}

	/**
	 * 得到系统当前时间
	 * 
	 * @return：
	 */
	public static String getCurrDate() {

		Calendar clen = Calendar.getInstance(Locale.CHINESE);
		Date sdate = clen.getTime();
		String strDate = new java.sql.Timestamp(sdate.getTime()).toString()
				.substring(0, 10);
		return strDate;
	}

	/**
	 * 转换转意字符
	 * 
	 * @param str
	 * @return
	 */
	public static String safeStringConvert(String str) {
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < str.length(); i++) {
			if (str.charAt(i) == '\\') {
				sb.append("\\\\");
			} else {
				sb.append(str.charAt(i));
			}
		}

		return sb.toString();
	}

	/**
	 * 格式化数字 for 出现科学计数法
	 * 
	 * @param number
	 *            要格式的数字
	 * @param text
	 *            格式
	 * @return 字符串
	 */
	public static String formatDouble(double number, String text) {
		if (text == null || text.equals("")) {
			text = "##.##";
		}
		java.text.DecimalFormat df = new java.text.DecimalFormat(text);
		return df.format(number);

	}

	public static String formatDouble(String number, String text) {
		if (number == null) {
			return "0.00";
		}
		if (text == null || text.equals("")) {
			text = "##.##";
		}
		java.text.DecimalFormat df = new java.text.DecimalFormat(text);
		return df.format(Double.parseDouble(number));

	}

	/**
	 * @param source
	 *            需要处理的源字符串
	 * @param len
	 *            截取的字符长度
	 * @return 截取len的长度的字符，一个汉字为两个字符处理，防止截取时出现乱码
	 * @author liyimin 2006/03/31 目前测试没有发现问题
	 */
	public static String splitString(String source, int len) {
		StringBuffer sb = new StringBuffer();
		int lentemp = 0;
		char c = 0;
		int i = 0;
		//
		// String encoding = System.getProperty("file.encoding");

		while (i < source.length()) {
			c = source.charAt(i);
			if (c < 128) {
				lentemp++;
			} else {
				lentemp += 2;
			}

			if (lentemp > len) {
				break;
			}

			sb.append(c);
			i++;
		}
		return sb.toString();
	}

	public static int strlen2(String source) {
		try {
			int len = 0;
			if (source == null) {
				return 0;
			}
			byte[] b = source.getBytes();
			len = b.length;

			return len;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * @param source
	 *            需要处理的源字符串
	 * @param len
	 *            截取的字符长度
	 * @return 截取len的长度的字符，一个汉字为两个字符处理，防止截取时出现乱码,并在后面加省略号
	 * @author LiuGan 2005/08/04
	 */
	public static String splitStringEllipsis(String source, int len) {
		try {
			if (source == null) {
				return "";
			}
			int counter = 0;
			byte[] b = source.getBytes();
			String attachment = "";
			if (b.length > len) {
				attachment = "...";
			}
			len = b.length > len ? len : b.length;
			for (int i = 0; i < len; i++) {
				if (b[i] < 0) {
					counter++;
				}
			}
			StringBuffer retuStr = new StringBuffer("");
			String str = (counter % 2 == 0) ? new String(b, 0, len)
					: new String(b, 0, len - 1);
			retuStr.append(str);
			retuStr.append(attachment);
			return retuStr.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 去掉源字符串，中包含的一些特殊字符，如ascii code 为10,13的字符
	 * 
	 * @param originStr
	 * @return
	 */
	public static String deleteIllegalChar(String originStr) {
		int[] illegalChar = { 10, 13 };
		StringBuffer toStr = new StringBuffer();

		for (int i = 0; i < illegalChar.length; i++) {
			int ascii = illegalChar[i];
			toStr = new StringBuffer();

			while (originStr.length() > 0 && originStr.indexOf(ascii) > -1) {
				if (originStr.indexOf(ascii) > 0) {
					toStr.append(originStr.substring(0, originStr
							.indexOf(ascii)));
				}

				// --找到的字符在字符串的最后，则把最后的字符去掉
				originStr = (originStr.indexOf(ascii) < originStr.length() - 1) ? originStr
						.substring(originStr.indexOf(ascii) + 1)
						: originStr.substring(0, originStr.length() - 1);
			}
			if (originStr.length() > 0) {
				toStr.append(originStr);
			}

			originStr = toStr.toString();
		}

		return toStr.toString();
	}

	public static String safeNumber(Object o) {
		if (null == o) {
			return "";
		}
		try {
			Double d = new Double(o.toString());
			return roundNumber2(d, 4);
		} catch (Exception ex) {

		}

		return o.toString();

	}

	public static String safeNumber(Object o, int n) {
		if (null == o) {
			return "";
		}
		try {
			Double d = new Double(o.toString());
			return roundNumber2(d, n);
		} catch (Exception ex) {

		}

		return o.toString();

	}

	public final static String[] SplitString(String sourceStr, String s) {
		StringTokenizer stk = new StringTokenizer(sourceStr, s);
		String[] strs = new String[stk.countTokens()];

		int i = 0;
		while (stk.hasMoreElements()) {
			strs[i] = stk.nextToken();
			i++;
		}

		return strs;
	}

	/**
	 * 两double数相加 使用BigDecimal运算，不出现误差
	 * 
	 * @param d1
	 *            double
	 * @param d2
	 *            double
	 * @return double
	 */
	public static double doubleAdd(double d1, double d2) {
		BigDecimal bigd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bigd2 = new BigDecimal(Double.toString(d2));

		return bigd1.add(bigd2).doubleValue();
	}

	/**
	 * 两double数相乘 使用BigDecimal运算，不出现误差
	 * 
	 * @param d1
	 *            double
	 * @param d2
	 *            double
	 * @return double
	 */
	public static double doubleMul(double d1, double d2) {
		BigDecimal bigd1 = new BigDecimal(Double.toString(d1));
		BigDecimal bigd2 = new BigDecimal(Double.toString(d2));

		return bigd1.multiply(bigd2).doubleValue();
	}

	/**
	 * 判断字符是否为数字,带有科学计数法的数字或8,16进制的数没有判断
	 * 
	 * @param str
	 *            String
	 * @return boolean
	 */
	public static boolean isNumber(String str) {
		try {
			if (null == str || "".equals(str.trim())) {
				return false;
			}
			Double.parseDouble(str);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	public static String safeSqlString(String str) {
		str = safeString(str);
		String tmp = str;
		str = str.toLowerCase();
		if (str.indexOf("drop") > 0) {
			return "";
		}
		if (str.indexOf("delete") > 0) {
			return "";
		}
		if (str.indexOf("add") > 0) {
			return "";
		}
		if (str.indexOf("update") > 0) {
			return "";
		}
		if (str.indexOf("select") > 0) {
			return "";
		}
		return tmp;
	}

}
